
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from "react-router-dom";
import HeaderTitle from "../login/header";
import style from "./index.module.less"
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons"
import React, { Fragment, useState, useEffect } from 'react'
import {
	Form,
	Input,
	Checkbox,
	Button,
	Toast,

} from 'antd-mobile'
import { register ,rmsgcode, getsysconfig} from "@/apis/user.js"

import logo from '../../static/Q9.png'

 
const Register = (props) => {
	const { t, i18n } = useTranslation();
	const BASE_URL = import.meta.env.VITE_BASE_URL;
	const navigate = useNavigate()
	const [visible, setVisible] = useState(false)
	const [formData, setFormData] = useState({ name: '', password: '', username: '', phone: '', code: '', Cpassword: '' })
	const [form] = Form.useForm()
	const [sitelogo,setsitelogo] = useState('')
	const [time,settime] = useState(60)
	const [countdown, setCountdown] = useState(120); 
	const [isCounting, setIsCounting] = useState(false); 
	useEffect(() => {
		const handleScroll = (event)=>{
			event.preventDefault();
			event.stopPropagation();
			window.scrollTo(0,0)
		}
		if(!localStorage.getItem('lang')){
			localStorage.setItem('lang', 'hk')
			localStorage.setItem('langs','0')
		}
		i18n.changeLanguage(localStorage.getItem('lang'))
		getsysconfig().then(res => {
			if (res.status.errorCode == 0) {
				localStorage.setItem("config",JSON.stringify(res.data))
				setsitelogo(res.data.site_logo)
			}
		})
		if(localStorage.getItem('config')){
			setsitelogo(JSON.parse(localStorage.getItem('config')).site_logo || '')
		}
		document.body.addEventListener('touchmove',handleScroll)
		return ()=>{
			console.log('初始化----注册')
			document.body.removeEventListener('touchmove',handleScroll)
		}
	  }, []);
	  useEffect(() => {
		let timer;
		if (isCounting && countdown > 0) {
		  timer = setTimeout(() => {
			setCountdown(countdown - 1);
		  }, 1000);
		} else if (countdown === 0) {
		  setIsCounting(false);
		  setCountdown(120); 
		}
		return () => {
		  clearTimeout(timer);
		};
	  }, [isCounting, countdown]);
	const onFinish = (values) => {
		console.log(values, 'values')
		Toast.show({
			icon: 'loading',
			content: '加载中',
		  })
		const valuesTow = { name: values.name, password: values.password, real_name:  values.username,
		 phone:  values.phone, code: values.code, Cpassword:  values.Cpassword }
		/*
			1.调用登录接口
			2.登录成功之后，看其是否勾选了记住密码，如果记住密码则将账号密码缓存在内存中
			3.下次进入秘密
		*/
	};
	

	const onFinishFailed = (errorInfo) => {
		console.log('Failed:', errorInfo);
	};
	
	  const Rmsgcode=(current)=>{
	  	// event.stopPropagation() // 阻止事件冒泡
		console.log('Failed:', current);
		if(current.length != 8){
			Toast.show({
				icon: 'fail',
				content: t('register.title11'),
			})
			return
		}
		if(current && !isCounting){
			rmsgcode({
				phone:current
			}).then(res => {
				if (res.status.errorCode == 0) {
					Toast.show({
						icon: 'success',
						content: res.status.msg,
					})
					setIsCounting(true);
				} else {
					Toast.show({
						icon: 'fail',
						content: res.status.msg,
					})
				}
			})
		}else{
			Toast.show({
				icon: 'fail',
				content: t('register.title10'),
			})
		}
		
	  };

	  const restFun = async ()=>{
		let t = await form.validateFields()
		if(t){
			register(form.getFieldValue()).then(res => {
				if (res.status.errorCode == 0) {
					localStorage.setItem('login',1)
					localStorage.setItem('token',res.data)
					Toast.show({
						icon: 'success',
						content: res.status.msg,
					})
					navigate('/index')
				} else {
					Toast.show({
						icon: 'fail',
						content: res.status.msg,
					})
	
				}
			})
		}
	  }
	// <Form.Item
	// 	label={t('register.title12')}
	// 	name='code'
	// 	rules={[{ required: true, message: t('register.title13') },
	// 	{ pattern: /^(?=\w*\d)(?=\w*[0-9])[\w]{4,6}$/, message: t('register.title13')}]}
	// >
	// 	<div style={{display:'flex'}}>
	// 		<Input style={{flex:'1'}} placeholder={t('register.title15')} />
	// 		{
	// 			time == 60 ? (<div className={style['sendmsg']} onClick={() => sendmsg()}>{t('register.title14')}</div>) : (<div className={style['sendmsg']}>{time}s</div>)
	// 		}
	// 	</div>
	// </Form.Item>
	return (
		<React.Fragment>
			<HeaderTitle title={t('register.title1')} right_title={t('agent.title2')}/>
			<div className={style['login_box']}>
				<div className={style['a2']}>
				<div style={{ textAlign: 'center' }}>
					<img src={logo} alt="" />
				</div>
				<Form
					form={form}
					layout='horizontal'
					onFinish={onFinish}
					 ref={formData}
					initialValues={formData}
				>
					<Form.Item
						label={t('register.title2')}
						name='name'
						rules={[{ required: true, message: t('register.title3') },
						{ pattern: /^(?=\w*\d)(?=\w*[a-zA-Z])[\w]{6,12}$/, message: t('register.title4') }]}
					>
						<Input placeholder={t('register.title5')} />
					</Form.Item>
					<Form.Item
						label={t('register.title6')}
						name='username'
						rules={[{ required: true, message:t('register.title7')  }]}
					>
						<Input placeholder={t('register.title8')} />
					</Form.Item>
					<Form.Item
						label={t('register.title9')}
						name='phone'
						rules={[{ required: true, message: t('register.title10') },
						{ pattern: /^(?=\w*\d)(?=\w*[0-9])[\w]{8,8}$/, message: t('register.title25')}]}
						extra={
							<div style={{ color: '#e38a00' }} 
							onClick={() => { if (!isCounting) Rmsgcode(phone.value); }}>{
								isCounting ? countdown + '秒'  :  t('register.title14')
							}</div>
						}
					>
						<Input placeholder={t('register.title11')} />
					</Form.Item>
					<Form.Item
						label={t('register.title12')}
						name='code'
						rules={[{ required: true, message: t('register.title13') }]}
					>
						<Input placeholder={t('register.title15')} />
					</Form.Item>
					
					<Form.Item
						label={t('register.title16')}
						name='password'
						rules={[{ required: true, message:t('register.title17') },
						{ pattern: /^(?=\w*\d)(?=\w*[a-zA-Z0-9])[\w]{6,16}$/, message: t('register.title21')}]}
						extra={
							<div>
								{!visible ? (
									<EyeInvisibleOutline onClick={() => setVisible(true)} />
								) : (
									<EyeOutline onClick={() => setVisible(false)} />
								)}
							</div>
						}>
						<Input placeholder={t('register.title18')} type={visible ? 'text' : 'password'} />
					</Form.Item>
					<Form.Item
						label={t('register.title19')}
						name='Cpassword'
						rules={[{ required: true, message: t('register.title20') },
						{ pattern: /^(?=\w*\d)(?=\w*[a-zA-Z0-9])[\w]{6,16}$/, message: t('register.title21')}]}
						extra={
							<div>
								{!visible ? (
									<EyeInvisibleOutline onClick={() => setVisible(true)} />
								) : (
									<EyeOutline onClick={() => setVisible(false)} />
								)}
							</div>
						}>
						<Input placeholder={t('register.title22')} type={visible ? 'text' : 'password'} />
					</Form.Item>
				</Form>
				<React.Fragment>
					<Button shape='rounded' className={style['btns']} style={{ marginBottom: '15px', marginTop: '15px' }} block onClick={() => {
						restFun()
					}} color='primary'>
						{t('register.title23')}
					</Button>
					<p className={style['other-info']} onClick={() => navigate('/login')}>{t('register.title24')}</p>

				</React.Fragment>
				</div>
			</div>
		</React.Fragment>

	)
}


export default Register
